package 网络.UDP;


import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPClient {
    public static void main(String[] args) throws Exception{
        try {
            // 创建一个DatagramSocket对象，用于发送数据
            DatagramSocket clientSocket = new DatagramSocket();
            System.out.println("客户端启动");

            // 将要发送的消息转换为字节
            String sentence = "Hello Server!";
            byte[] sendData = sentence.getBytes();
            InetAddress IPAddress = InetAddress.getByName("localhost"); // 服务器地址
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876); // 服务器端口号

            // 发送数据
            clientSocket.send(sendPacket);
            System.out.println("客户端：消息已发送");

            // 接收服务器响应
            byte[] receiveData = new byte[1024];
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

            clientSocket.receive(receivePacket);

            String modifiedSentence = new String(receivePacket.getData(), 0, receivePacket.getLength());
            System.out.println("客户端收到：" + modifiedSentence);
            // 关闭连接
            clientSocket.close();
        } catch (IOException e) {
            System.err.println("客户端异常：" + e.getMessage());
            e.printStackTrace();
        }
    }
}
